package io.summer.basis.core.http;

import org.springframework.http.client.SimpleClientHttpRequestFactory;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.IOException;
import java.net.HttpURLConnection;

/**
 * @author Moonlight
 * for resttemplate
 */
public class NoSslClientHttpRequestFactory extends SimpleClientHttpRequestFactory {
  @Override
  protected void prepareConnection(HttpURLConnection connection, String httpMethod)
    throws IOException {
    if (connection instanceof HttpsURLConnection) {
      prepareHttpsConnection((HttpsURLConnection) connection);
    }
    super.prepareConnection(connection, httpMethod);
  }

  private void prepareHttpsConnection(HttpsURLConnection connection) {
    connection.setHostnameVerifier(new SkipHostnameVerifier());
    try {
      connection.setSSLSocketFactory(CustomSSLSocketFactory.socketFactory());
    } catch (Exception ignored) {
    }
  }

  private static class SkipHostnameVerifier implements HostnameVerifier {
    @Override
    public boolean verify(String s, SSLSession sslSession) {
      return true;
    }
  }
}
